<?php
namespace App\Services;
use App\Models\HoneyBalance;
use App\Models\User;
use Illuminate\Support\Facades\DB;

class HoneyBalanceService {

    public static function store($user_id, $total_amount, $type, $entity_id = 0, $is_transaction = true) {
        $is_transaction && DB::beginTransaction();
        try {
            $user = User::lockForUpdate()->find($user_id);
            if ($user) {
                $balanceModel = HoneyBalance::where('user_id', $user_id)->orderBy('id', 'desc')->first();
                $balance = ($balanceModel->balance ?? 0) + $total_amount ;
                HoneyBalance::create([
                    'entity_id' => $entity_id,
                    'user_id' => $user_id,
                    'type' => $type,
                    'amount' => $total_amount,
                    'balance' => $balance
                ]);
                $user->honey_balance = $balance;
                $user->save();
            }
            $is_transaction && DB::commit();
        } catch (\Exception $e) {
            $is_transaction && DB::rollBack();
            throw new \Exception($e->getMessage());
        }
    }

}
